package com.j.lemon.learn.thread.CAS;

import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceDemo1 {
        public static final  AtomicReference<Integer> i = new AtomicReference<>();

    public static void main(String[] args) {

        i.set(19);
        for(int j =0;j<3;j++){
            new Thread(() -> {
                while(true){
                        Integer m = i.get();
                        if(m<20){
                            if(i.compareAndSet(m,m+20)){
                                System.out.println("充值20，余额："+i.get());
                                break;
                            }
                        }else{
                            System.out.println("m>20无需充值");
                            break;
                        }
                }
            }).start();

            new Thread(() -> {
                while(true){
                    Integer m = i.get();
                    if(m>10){
                        System.out.println("金额大于10元");
                        if(i.compareAndSet(m, m - 10)) {
                            System.out.println("消费10元，剩余："+i.get());
                            break;
                        }
                    }else{
                        System.out.println("余额不足10元");
                        break;
                    }
                }
            }).start();
        }


    }
}
